import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'dart:collection';
import '../models/period_model.dart';
import 'data_service.dart';
import 'period_service.dart';
import 'error_handler.dart';
import '../utils/errors.dart';

// 定义状态变更类型
enum AppStateChangeType {
  periodRecords,
  userProfile,
  periodActive,
  minimalistMode,
  loading,
  initialized
}

// 状态变更监听器类型
typedef AppStateChangeListener = void Function(AppStateChangeType changeType);

class AppStateNotifier extends ChangeNotifier {
  // 单例模式实现
  static final AppStateNotifier _instance = AppStateNotifier._internal();
  factory AppStateNotifier() => _instance;
  
  // 数据服务依赖
  final DataService _dataService = DataService();
  final PeriodService _periodService = PeriodService();
  // final PredictionService _predictionService = PredictionService(); // 未使用，注释掉
  final ErrorHandler _errorHandler = ErrorHandler();
  
  // 应用状态
  List<PeriodModel> _periodRecords = [];
  UserProfile? _userProfile;
  bool _isPeriodActive = false;
  bool _isMinimalistMode = false;
  bool _isInitialized = false;
  bool _isLoading = false;
  
  // 状态变更监听器映射
  final Map<AppStateChangeType, List<AppStateChangeListener>> _listeners = {};
  
  // 数据缓存和计时器
  final Map<String, dynamic> _dataCache = {};
  final Map<String, DateTime> _cacheTimestamps = {};
  Timer? _debounceTimer;
  static const Duration _cacheDuration = Duration(minutes: 5);
  
  // 获取器
  UnmodifiableListView<PeriodModel> get periodRecords => UnmodifiableListView(_periodRecords);
  UserProfile? get userProfile => _userProfile;
  bool get isPeriodActive => _isPeriodActive;
  bool get isMinimalistMode => _isMinimalistMode;
  bool get isInitialized => _isInitialized;
  bool get isLoading => _isLoading;
  
  AppStateNotifier._internal() {
    _initializeListenersMap();
  }
  
  void _initializeListenersMap() {
    for (var type in AppStateChangeType.values) {
      _listeners[type] = [];
    }
  }
  
  // 添加特定类型的状态变更监听器
  void addChangeListener(AppStateChangeType type, AppStateChangeListener listener) {
    if (!_listeners.containsKey(type)) {
      _listeners[type] = [];
    }
    _listeners[type]!.add(listener);
  }
  
  // 移除特定类型的状态变更监听器
  void removeChangeListener(AppStateChangeType type, AppStateChangeListener listener) {
    if (_listeners.containsKey(type)) {
      _listeners[type]!.remove(listener);
    }
  }
  
  // 通知特定类型的状态变更
  void _notifyChange(AppStateChangeType type) {
    if (_listeners.containsKey(type)) {
      for (var listener in _listeners[type]!) {
        try {
          listener(type);
        } catch (e) {
          _errorHandler.handleError(e, 'AppStateNotifier._notifyChange');
        }
      }
    }
    
    // 触发全局变更通知（用于UI更新）
    _debouncedNotifyListeners();
  }
  
  // 防抖通知UI更新
  void _debouncedNotifyListeners() {
    _debounceTimer?.cancel();
    _debounceTimer = Timer(const Duration(milliseconds: 100), () {
      try {
        notifyListeners();
      } catch (e) {
        _errorHandler.handleError(e, 'AppStateNotifier._debouncedNotifyListeners');
      }
    });
  }
  
  // 初始化应用数据
  Future<void> initializeApp() async {
    return _safeOperation(() async {
      _setLoading(true);
      
      // 初始化数据服务
      await _dataService.initialize();
      
      // 并行加载数据以提高性能
      await Future.wait([
        _loadMinimalistMode(),
        _loadData(),
      ]);
      
      // 设置初始化完成标志
      _isInitialized = true;
      _notifyChange(AppStateChangeType.initialized);
      
      _setLoading(false);
    }, 'initializeApp',
    onError: () {
      // 创建可恢复的错误
      final appError = AppError(
        message: '初始化应用失败',
        type: AppErrorType.unknown,
        isRecoverable: true,
      );
      appError.retryCallback = initializeApp;
    });
  }
  
  // 加载极简模式设置
  Future<void> _loadMinimalistMode() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      _isMinimalistMode = prefs.getBool('isMinimalistMode') ?? false;
      _notifyChange(AppStateChangeType.minimalistMode);
    } catch (e) {
      _errorHandler.handleError(e, '_loadMinimalistMode');
      // 使用默认值
      _isMinimalistMode = false;
    }
  }
  
  // 安全操作封装
  Future<void> _safeOperation(
    Future<void> Function() operation,
    String operationName,
    {void Function()? onError}
  ) async {
    try {
      await operation();
    } catch (e) {
      _errorHandler.handleError(e, operationName);
      if (onError != null) {
        onError();
      }
      rethrow;
    } finally {
      _setLoading(false);
    }
  }
  
  // 设置加载状态
  void _setLoading(bool value) {
    if (_isLoading != value) {
      _isLoading = value;
      _notifyChange(AppStateChangeType.loading);
    }
  }
  
  // 加载数据
  Future<void> _loadData() async {
    try {
      // 并行加载数据
      final futureResults = await Future.wait(<Future<dynamic>>[
        _dataService.loadUserProfile(),
        _dataService.loadPeriodRecords(),
        // 先获取用户档案来获取userId
        Future.microtask(() async {
          final userProfile = await _dataService.loadUserProfile();
          if (userProfile?.id != null) {
            return await _periodService.isPeriodActiveToday(userProfile!.id!).catchError((e) {
              _errorHandler.handleError(e, '_loadData.isPeriodActiveToday');
              return false;
            });
          }
          return false;
        })
      ]);
      
      // 更新用户资料
      _updateUserProfile(futureResults[0] as UserProfile?);
      
      // 更新周期记录
      _updatePeriodRecords(futureResults[1] as List<PeriodModel>);
      
      // 更新经期活动状态
      _updatePeriodActiveStatus(futureResults[2] as bool);
      
    } catch (e) {
      _errorHandler.handleError(e, '_loadData');
      // 使用默认值作为后备
      if (_periodRecords.isEmpty) {
        _periodRecords = [];
      }
    }
  }
  
  // 更新用户档案
  void _updateUserProfile(UserProfile? profile) {
    _userProfile = profile;
    _notifyChange(AppStateChangeType.userProfile);
  }
  
  // 更新经期记录
  void _updatePeriodRecords(List<PeriodModel> records) {
    _periodRecords = List.from(records);
    _notifyChange(AppStateChangeType.periodRecords);
  }
  
  // 更新经期活动状态
  void _updatePeriodActiveStatus(bool isActive) {
    if (_isPeriodActive != isActive) {
      _isPeriodActive = isActive;
      _notifyChange(AppStateChangeType.periodActive);
    }
  }
  
  // 获取月份数据（带缓存优化）
  Future<List<PeriodModel>> getMonthData(DateTime date) async {
    try {
      final cacheKey = 'month_${date.year}_${date.month}';
      
      // 检查缓存是否有效
      if (_isCacheValid(cacheKey)) {
        return _dataCache[cacheKey] as List<PeriodModel>;
      }
      
      final monthData = await _errorHandler.safeOperation<List<PeriodModel>>(
        () async {
          return await _periodService.getMonthData(date.year, date.month);
        },
        'getMonthData',
        fallbackValue: () {
          // 返回空数据而不是null
          return <PeriodModel>[];
        },
      );
      
      // 更新缓存
      _updateCache(cacheKey, monthData);
      
      return monthData;
    } catch (e) {
      _errorHandler.handleError(e, 'getMonthData');
      return [];
    }
  }
  
  // 缓存相关方法
  bool _isCacheValid(String key) {
    if (!_cacheTimestamps.containsKey(key)) {
      return false;
    }
    final timestamp = _cacheTimestamps[key];
    if (timestamp == null) {
      return false;
    }
    return DateTime.now().difference(timestamp) < _cacheDuration;
  }
  
  void _updateCache(String key, dynamic value) {
    _dataCache[key] = value;
    _cacheTimestamps[key] = DateTime.now();
  }
  
  void _clearMonthCache(DateTime date) {
    final cacheKey = 'month_${date.year}_${date.month}';
    _dataCache.remove(cacheKey);
    _cacheTimestamps.remove(cacheKey);
  }
  
  // 清除特定缓存
  void clearCache({String? key}) {
    if (key != null) {
      _dataCache.remove(key);
      _cacheTimestamps.remove(key);
    } else {
      _dataCache.clear();
      _cacheTimestamps.clear();
    }
  }
  
  // 保存周期记录
  Future<void> savePeriodRecord(PeriodModel record) async {
    return _safeOperation(() async {
      _setLoading(true);
      
      await _dataService.savePeriodRecord(record);
      await _loadData(); // 重新加载数据以更新状态
      
      // 清除相关月份缓存
      _clearMonthCache(record.date);
      
    }, 'savePeriodRecord',
    onError: () {
      // 创建可恢复的错误
      final appError = AppError(
        message: '保存记录失败',
        type: AppErrorType.database,
        isRecoverable: true,
      );
      appError.retryCallback = () => savePeriodRecord(record);
    });
  }
  
  // 记录经期开始（便捷方法）
  Future<void> recordPeriodStart(DateTime date, {String? notes}) async {
    final record = PeriodModel(
      id: DateTime.now().millisecondsSinceEpoch,
      date: date,
      isPeriod: true,
      isOvulation: false,
      isToday: false,
      isPredictedPeriod: false,
      isPossiblePeriod: false,
      notes: notes,
    );
    return savePeriodRecord(record);
  }
  
  // 记录经期结束（便捷方法）
  Future<void> recordPeriodEnd(DateTime date, {String? notes}) async {
    final record = PeriodModel(
      id: DateTime.now().millisecondsSinceEpoch,
      date: date,
      isPeriod: true,
      isOvulation: false,
      isToday: false,
      isPredictedPeriod: false,
      isPossiblePeriod: false,
      notes: notes,
    );
    return savePeriodRecord(record);
  }
  
  // 更新用户资料
  Future<void> updateUserProfile(UserProfile profile) async {
    return _safeOperation(() async {
      _setLoading(true);
      
      await _dataService.saveUserProfile(profile);
      _updateUserProfile(profile);
      
      // 清除缓存以确保下次获取最新数据
      clearCache();
      
    }, 'updateUserProfile',
    onError: () {
      // 创建可恢复的错误
      final appError = AppError(
        message: '更新用户资料失败',
        type: AppErrorType.database,
        isRecoverable: true,
      );
      appError.retryCallback = () => updateUserProfile(profile);
    });
  }
  
  // 设置极简模式
  Future<void> setMinimalistMode(bool value) async {
    try {
      if (_isMinimalistMode != value) {
        // 直接使用SharedPreferences设置极简模式
        final prefs = await SharedPreferences.getInstance();
        await prefs.setBool('isMinimalistMode', value);
        _isMinimalistMode = value;
        _notifyChange(AppStateChangeType.minimalistMode);
      }
    } catch (e) {
      _errorHandler.handleError(e, 'setMinimalistMode');
      rethrow;
    }
  }
  
  // 清除所有数据
  Future<void> clearAllData() async {
    return _safeOperation(() async {
      _setLoading(true);
      
      await _dataService.clearAllData();
      
      // 重置所有状态
      _updatePeriodRecords([]);
      _updateUserProfile(null);
      _updatePeriodActiveStatus(false);
      
      // 清除缓存
      clearCache();
      
    }, 'clearAllData');
  }
  
  @override
  void dispose() {
    _debounceTimer?.cancel();
    _listeners.clear();
    _dataCache.clear();
    _cacheTimestamps.clear();
    super.dispose();
  }
}